@echo off

chcp 1251

SET MY_DIR=%~dp0

SET PATH=%MY_DIR%LIB;%PATH%

SET SCRIPT_PATH=%~1
SET SCRIPT_DIR=%~dp1
SET SCRIPT_NAME=%~n1

SET SELECT_DELAY=%~2
IF NOT "%SELECT_DELAY%"=="n" SET SELECT_DELAY=y

SET O_MSG=!E_MSG!

call %MY_DIR%defvars.bat || GOTO endscript
call %MY_DIR%utl.bat chexist "%SCRIPT_PATH%" || GOTO endscript

echo ****** Encoding %SCRIPT_PATH% 
echo ****** Job started at %DATE% %TIME%


SETLOCAL ENABLEDELAYEDEXPANSION

CALL %MY_DIR%utl.bat updver || GOTO endscript

echo x264 version: %avs_x264_ver%
echo Nero AAC version: %avs_neroaac_ver%
echo MP4Box version: %avs_mp4box_ver%

ENDLOCAL

FOR /F "usebackq eol=# delims== tokens=1,2" %%i IN (`%LOW_PRIORITY% "%OPENAVS_PATH%" -f "%SCRIPT_PATH%" -p avs_mux_path avs_audio_path avs_video_path avs_stats1_path avs_stats2_path avs_audio_cmd avs_pass_1_cmd avs_pass_2_cmd avs_pass_3_cmd avs_clip_num`) DO SET %%i=%%~j

SETLOCAL ENABLEDELAYEDEXPANSION


IF "%avs_clip_num%"=="" SET avs_clip_num=1
IF "%avs_clip_num%"=="0" SET avs_clip_num=1

SET /A avs_clip_num=%avs_clip_num%+1
SET CLIP_NO=0

:enccliploop

SET A_STRING=%avs_delays_list%
SET A_TOKEN=

SET /A CLIP_NO=%CLIP_NO%+1
IF "%CLIP_NO%"=="%avs_clip_num%" GOTO endjob

:encloop

CALL %MY_DIR%utl.bat gettoken "%A_STRING%" || GOTO endscript

SET A_STRING=%GT_STRING%
IF "%GT_TOKEN%"=="q" GOTO enccliploop

IF "%GT_TOKEN%"=="" SET GT_TOKEN=0

SET /A A_DELAY=%GT_TOKEN%

FOR /F "usebackq eol=# delims== tokens=1,2" %%i IN (`%LOW_PRIORITY% "%OPENAVS_PATH%" -v "avs_clip_no=%CLIP_NO%" -f "%SCRIPT_PATH%" -p avs_clip_name avs_frames_num avs_framerate avs_video_bitrate avs_audio_bitrate avs_audio_num avs_passes_num avs_delays_list avs_ripper`) DO SET %%i=%%~j
IF "%avs_clip_name%"=="" SET CLIP_NAME=%SCRIPT_NAME%
IF NOT "%avs_clip_name%"=="" SET CLIP_NAME=%avs_clip_name%

CALL %MY_DIR%utl.bat rawaenc y %A_DELAY% %CLIP_NO% || GOTO endscript
CALL %MY_DIR%utl.bat defamuxcmd %A_DELAY% %CLIP_NO% || GOTO endscript

IF "%A_DELAY%"=="0" CALL %MY_DIR%utl.bat rawvenc y y y %CLIP_NO% || GOTO endscript
IF "%A_DELAY%"=="0" CALL %MY_DIR%utl.bat defvmuxcmd %CLIP_NO% || GOTO endscript

IF "%A_DELAY%"=="0" CALL %MY_DIR%utl.bat rawmux y || GOTO endscript
IF NOT "%A_DELAY%"=="0" CALL %MY_DIR%utl.bat rawmux y ".%A_DELAY%" || GOTO endscript

IF NOT "%A_STRING%"=="" GOTO encloop

IF NOT "%SELECT_DELAY%"=="y" GOTO enccliploop

ECHO Enter new audio delay or 'q' for exit...
SET /P A_STRING=
GOTO encloop

:endjob
SET O_MSG=!S_MSG!

:endscript

IF "!O_MSG!"=="!S_MSG!" COLOR 2F
IF NOT "!O_MSG!"=="!S_MSG!" COLOR 4F

echo !O_MSG!
echo ****** Job ended at %DATE% %TIME% 
ENDLOCAL

exit /b 0

